// routes/auth.js
const express = require('express');
const jwt = require('jsonwebtoken');
const UserModel = require('../models/userModel');
const bcrypt = require('bcrypt');
// const { createClient } = require('redis');

module.exports = (db) => {
    const router = express.Router();
    const userModel = new UserModel(db);

    // POST 用户注册
    router.post('/register', async (req, res) => {
        const { name, email, password } = req.body;
        try {
            const userId = await userModel.createUser(name, email, password);
            res.status(201).json({
                code: 201,
                success: true,
                // message: 'User registered successfully',
                data: { id: userId, name, email },
            });
        } catch (error) {
            res.status(500).json({
                code: 500,
                success: false,
                // message: 'Error registering user',
                error: 'Error registering user',
            });
        }
    });

    // POST 用户登录
    router.post('/login', async (req, res) => {
        // const client = createClient({
        //     url: 'redis://127.0.0.1:6379'
        // });

        // // 连接到 Redis
        // await client.connect();
        const { email, password } = req.body;
        try {
            console.log('email--',email);
            console.log('password--',password);
            
            const user = await userModel.getUserByEmail(email);
            console.log('user--',user);
            
            if (!user || !(await bcrypt.compare(password, user.password))) {
                return res.status(401).json({
                    code: 401,
                    success: false,
                    message: 'Invalid credentials',
                });
            }
            console.log('user--',user);
            
            const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET, { expiresIn: '1h' });

            // client.setex(`token:${user.id}`, 7 * 24 * 60 * 60, token);

            // await client.set(`token:${user.id}`, token, { EX: 7 * 24 * 60 * 60 }); // 15 分钟



            res.json({
                code: 200,
                success: true,
                message: 'Login successful',
                token,
            });
        } catch (error) {
            console.log('error---',error);
            
            res.status(500).json({
                code: 500,
                success: false,
                message: 'Error logging in',
                error: error.message,
            });
        }
    });

    return router;
};